using System;
using QAssetBundle;
using UnityEngine;
using QFramework;
using QFramework.Example;
using UnityEngine.WSA;

namespace XCZProject
{
	public partial class Player : ViewController
	{
		public float MovementSpeed = 8; // 移动速度 

		public static Player Default; // 角色实例

		public AudioPlayer mWalkSfx; // 角色移动音效

		private void Awake()
		{
			Default = this;
		}

		private void OnDestroy()
		{
			Default = null;
		}

		void Start()
		{
			// Code Here
            "开始游戏".LogInfo();

            HurtBox.OnTriggerEnter2DEvent((collider2D =>
            {
	            // 获取碰撞到的物体上的hitBox脚本
	            var hitBox = collider2D.GetComponent<HitBox>();
	            // 如果hitBox存在，且hitBox中Owner的Tag是Enemy，则证明碰撞到的是敌人，则掉血或者死亡
	            if (hitBox)
	            {
		            if (hitBox.Owner.CompareTag("Enemy"))
		            {
			            Global.HP.Value--;
			            if (Global.HP.Value<=0)
			            {
				            AudioKit.PlaySound("die");
				            this.DestroyGameObjGracefully();

				            UIKit.OpenPanel<UIGameOverPanel>();
			            }
			            else
			            {
				            AudioKit.PlaySound("hurt");
			            }
		            }
	            }
            })).UnRegisterWhenGameObjectDestroyed(gameObject);

            Global.HP.RegisterWithInitValue(hp =>
            {
	            UpdateHp();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            Global.MaxHP.RegisterWithInitValue(maxhp =>
            {
	            UpdateHp();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		private void UpdateHp()
		{
			HpValue.fillAmount = Global.HP.Value / (float)Global.MaxHP.Value;
		}

		// 角色默认是朝向右边
		private bool mFaceRight = true;
		
		private void Update()
		{
			var horizontal =Input.GetAxisRaw("Horizontal");
			var vertical= Input.GetAxisRaw("Vertical");

			var targetVelocity = new Vector2(horizontal, vertical).normalized * (MovementSpeed * Global.MovementSpeedRate.Value);

			if (horizontal==0&&vertical==0)
			{
				// 如果两个都为0.则是idle状态
				if (mFaceRight)
				{
					Sprite.Play("PlayerIdleRight"); 
				}
				else
				{
					Sprite.Play("PlayerIdleLeft"); 
				}

				// 如果有移动音效，则在idle状态时需要停止播放，并且设置音效为空
				if (mWalkSfx!=null)
				{
					mWalkSfx.Stop();
					mWalkSfx = null;
				}
			}
			else
			{
				if (mWalkSfx==null)
				{
					mWalkSfx = AudioKit.PlaySound(Sfx.WALK, true);
				}
				
				// 判断方向
				if (horizontal>0)
				{
					mFaceRight = true;
				}
				else if(horizontal<0)
				{
					mFaceRight = false;
				}
				// 有一个不为0，就是移动状态
				if (mFaceRight)
				{
					Sprite.Play("PlayerWalkRight"); 
				}
				else
				{
					Sprite.Play("PlayerWalkLeft"); 
				}
			}
			
			SelfRigidbody2D.velocity =
				Vector2.Lerp(SelfRigidbody2D.velocity, targetVelocity,
					Mathf.Exp(-Time.timeScale * 5));
		}
	}
}
